#include "threadPool.h"

// 处理gets命令，即发送文件
int gets_work(const client_info_t *client_info)
{
    int netfd = client_info->netfd;

    // 接收客户端传来的路径path，需要手动截取文件名
    char path[1024] = {0};
    int path_len;
    recv(netfd, &path_len, sizeof(int), MSG_WAITALL);
    recv(netfd, path, path_len, MSG_WAITALL);
    char file_path[1024] = {0}; 
    if('/' == path[0]){
        //这是个绝对路径，拼接逻辑路径
        strcpy(file_path, client_info->virtual_global_path);
        strcat(file_path, path);
    }else{
        //这是个相对路径，拼接真实路径
        strcpy(file_path, client_info->global_path);
        strcat(file_path, path);
    }
    printf("绝对路径为%s\n", file_path);

    train_t train; // “小火车”
    bzero(&train, sizeof(train));
    int file_fd;
    // 接受客户端传来的关于这个文件是否已经下载过的信息
    // 如果下载过，那文件的大小是多少
    off_t seek_size = 0;
    recv(netfd, &train.len, sizeof(train.len), MSG_WAITALL);
    recv(netfd, train.data, train.len, MSG_WAITALL);
    memcpy(&seek_size, train.data, train.len);
    printf("seek_size: %ld\n", seek_size);
    if(seek_size != 0) {
        // 客户端下载过
        file_fd = open(file_path, O_RDWR);
        ERROR_CHECK(file_fd, -1, "open");
        lseek(file_fd, seek_size, SEEK_SET);
    } else {
        // 客户端没下载过
        file_fd = open(file_path, O_RDWR);
        ERROR_CHECK(file_fd, -1, "open");
    }

    // 获得剩余文件的大小，发送给客户端
    struct stat statbuf;
    fstat(file_fd, &statbuf);
    off_t tran_size = statbuf.st_size - seek_size;
    printf("tran_size: %ld\n", tran_size);
    send(netfd, &tran_size, sizeof(tran_size), MSG_NOSIGNAL); 

    if(tran_size >= BIGFILE) {
        // 大文件
        sendfile(netfd, file_fd, &seek_size, tran_size);
    } else {
        // 小文件
        while(1){
            ssize_t read_ret = read(file_fd, train.data, sizeof(train.data));
            if(read_ret == 0){
                break;
            }
            //断点重传测试用
           /*  printf("已传输：%ld\n", read_ret);
            sleep(5); */
            train.len = read_ret;
            send(netfd, &train, sizeof(train.len) + train.len, MSG_NOSIGNAL);
        }
    }
    train.len = 0;
    send(netfd, &train, sizeof(train.len) + train.len, MSG_NOSIGNAL);
    printf("文件传输完成！\n");
    // 关闭文件
    close(file_fd);

    return 0;
}